const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
// const SpeedMeasurePlugin = require("speed-measure-webpack-plugin");
// const smp = new SpeedMeasurePlugin();
// 分析包内容
const BundleAnalyzerPlugin =
  require("webpack-bundle-analyzer").BundleAnalyzerPlugin;

module.exports = {
  mode: "development",
  entry: {
    index: "./src/index.js",
    // print: "./src/print.js",
    // 如果 index 和 print 有共同的引入 那么会造成包重复 如何解决
    // index: {
    //   import: "./src/index.js",
    //   dependOn: "shared",
    // },
    // print: {
    //   import: "./src/print.js",
    //   dependOn: "shared",
    // },
    // // 共享的包-
    // // 打包后会生成一个 runtimer缓存贡献的包
    // shared: "lodash",
  },
  output: {
    // filename: "[name].bundle.js",
    filename: "[name].[contenthash].js",
    path: path.resolve(__dirname, "dist"),
    clean: true, // 构建前清除dist文件夹
    publicPath: "/",
  },

  // 也可以不适用 shared 打包 如下
  // optimization: {
  //   splitChunks: {
  //     chunks: "all",
  //   },
  // },

  module: {
    // i 表示匹配CSS 和 css 不区分大小写
    rules: [
      {
        test: /\.css$/i,
        use: ["style-loader", "css-loader"],
      },
      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        type: "asset/resource",
      },
      {
        test: /\.(woff|woff2|eot|ttf|otf)$/i,
        type: "asset/resource",
      },
    ],
  },
  devServer: {
    static: "./dist",
  },
  // 开发环境 错误映射
  devtool: "inline-source-map",
  plugins: [
    new HtmlWebpackPlugin({
      title: "Development",
    }),
    // new BundleAnalyzerPlugin(),
  ],

  // 单页面如果有多个入口的话需要通知webpack-dev-server 这样 optimization.runtimeChunk: 'single'
  optimization: {
    // 不论是否添加任何新的本地依赖，对于前后两次构建，vendor hash 都应该保持一致
    moduleIds: "deterministic",
    runtimeChunk: "single",
    // node_modules 长期缓存 因为他们不会频繁修改
    splitChunks: {
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: "vendors",
          chunks: "all",
        },
      },
    },
  },
};
